﻿using System.Runtime.InteropServices;
using System.Threading;

namespace ICRprojekt.Vibracija
{
    public static class LED
    {
        const int NLED_COUNT_INFO_ID = 0;
        const int NLED_SETTINGS_INFO_ID = 2;
        private static readonly int _ledCount;

        class NLED_SETTINGS_INFO
        {
            public uint LedNum;
            public uint OffOnBlink;
            public int TotalCycleTime;
            public int OnTime;
            public int OffTime;
            public int MetaCycleOn;
            public int MetaCycleOff;
        }

        class NLED_COUNT_INFO
        {
            public int cLeds;
        }

        public enum Status
        {
            OFF = 0,ON,BLINK
        }

        [DllImport("coredll.dll")]
        private static extern bool NLedGetDeviceInfo(uint nID, NLED_COUNT_INFO pOutput);
        [DllImport("coredll.dll")]
        private static extern bool NLedSetDevice(uint nID, NLED_SETTINGS_INFO pOutput);

        static LED()
        {
            _ledCount = GetLedCount();
        }

        public static void SetLedStatus(Status status)
        {
            var nsi = new NLED_SETTINGS_INFO {OffOnBlink = ( (uint) status )};

            for (int i = 0; i < _ledCount; i++)
            {
                nsi.LedNum = (uint)i;
                NLedSetDevice(NLED_SETTINGS_INFO_ID, nsi);
            }
        }

        public static void Vibrate(int millisecondsTimeout)
        {
            SetLedStatus(Status.ON);
            Thread.Sleep(millisecondsTimeout);
            SetLedStatus(Status.OFF);
        }

        private static int GetLedCount()
        {
            var count = 0;
            var nci = new NLED_COUNT_INFO();
            if (NLedGetDeviceInfo(NLED_COUNT_INFO_ID, nci))
            {
                count = nci.cLeds;
            }
            return count;
        }
    }
}
